package com.ionehe.group.common.uaa.ex.domain.service.impl;

import com.google.common.base.Throwables;
import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.sms.core.exception.RetryTimeShortException;
import com.ionehe.group.common.sms.service.VerificationCodeService;
import com.ionehe.group.common.uaa.ex.domain.service.SmsService;
import com.ionehe.group.common.uaa.ex.domain.service.UserReadService;
import com.ionehe.group.common.uaa.ex.enums.ErrorMessages;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * Copyright (c) 2020 moma有限公司
 * Date: 2020/12/15
 * Time: 10:05 上午
 *
 * @author 2020年 <a href="mailto:chenwd@moma.ai">秀</a>
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private UserReadService userInfoReadService;
    @Autowired(required = false)
    private VerificationCodeService verificationCodeService;

    @Override
    public Response<Boolean> getVerificationCode(String mobile, Integer terminal) {
        try {
            // 校验用户 是否存在
            if (Objects.nonNull(terminal)) {
                mobile = terminal + "_" + mobile;
            }

            //Response<UserDetails> userDetailsRes = userInfoReadService.loadUserByUsername(mobile);
            //if (!userDetailsRes.success()) {
            //    return Response.no(userDetailsRes.getMessage());
            //}
            //if (Objects.isNull(userDetailsRes.getData())) {
            //    return Response.no(ErrorMessages.USER_IS_NOT_EXIST.toString());
            //}

            // 发送验证码
            boolean send = verificationCodeService.send(mobile);

            if (!send) {
                return Response.no(ErrorMessages.SEND_VERIFICATION_CODE_FAIL.toString());
            }

            return Response.yes(true);
        } catch (RetryTimeShortException e){
            return Response.no(e.getMessage());
        }  catch (Exception e) {
            log.warn("send sms exception! cause:{}", Throwables.getStackTraceAsString(e));
            return Response.no(ErrorMessages.SEND_VERIFICATION_CODE_FAIL.toString());
        }
    }

    @Override
    public Response<Boolean> verify(Integer terminal, String mobile, String smsVerificationCode) {
        try {
            if (Objects.nonNull(terminal)) {
                mobile = terminal + "_" + mobile;
            }
            if (verificationCodeService.verify(mobile, smsVerificationCode, null)) {
                return Response.yes(true);
            }

            return Response.no("验证码有误!");
        } catch (Exception e) {
            log.warn("验证码校验异常！cause:{}", Throwables.getStackTraceAsString(e));
            return Response.no("验证码异常");
        }
    }
}
